package com.yicong.ants.ui.present;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

import androidx.annotation.Nullable;

import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.ui.activity.BaseStatefulActivity;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.databinding.ActivityVideoBinding;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.view.VideoPlayerView;

import java.util.List;
import java.util.Locale;
import java.util.Random;

import cn.jzvd.Jzvd;

/**
 * Description:
 *
 * @author Jun 2020/9/26
 */
public class VideoActivity extends BaseStatefulActivity<ActivityVideoBinding> {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarTransparent();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_video;
    }

    @Override
    protected void initEventAndData() {
        onLoadData();
    }

    @Override
    protected void onLoadData() {
        switchView(LOADING);
        addSubscribe(RetrofitHelper.getApis().adVideo()
            .compose(RxHelper.toMain())
            .subscribe(listRespBean -> {
                List<String> videoUrlList = listRespBean.getData();
                startVideoPlayer(videoUrlList);
                switchView(CONTENT);
            }, RxHelper.getHideProgressConsumer(this)));
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return keyCode == KeyEvent.KEYCODE_BACK;
    }

    /**
     * 开始播放视频
     *
     * @param videoUrlList
     */
    private void startVideoPlayer(List<String> videoUrlList) {
        if (videoUrlList == null || videoUrlList.size() == 0) {
            return;
        }

        // 随机取一个视频地址
        Random random = new Random();
        int randomPos = random.nextInt(videoUrlList.size());
        String videoUrl = videoUrlList.get(randomPos);

        VideoPlayerView player = mDataBind.videoPlayer;
        player.setUp(videoUrl, "");
        player.startVideo();
        player.setProgressListener((progress, position, duration) -> {
            // 计算视频播放时长倒序
            long currentTime = toTime(position);
            long totalTime = toTime(duration);
            long countDownTimer = totalTime - currentTime;
            // 设置视频播完时长
            mDataBind.videoTime.setVisibility(View.VISIBLE);
            mDataBind.videoTime.setText(String.format(Locale.ENGLISH, "%d", countDownTimer));

            // 播放视频结束，关闭界面
            if (countDownTimer <= 1) {
                RxBus.get().postEvent(getIntent().getIntExtra(Constants.Extra.Code, Constants.Event.Ants_Ad_Complete));
                finish();
            }

            // Log.d("VideoActivity", String.format("startVideoPlayer: progress = %d, position = %d, duration = %d", progress, position, duration));
            // Log.d("VideoActivity", String.format("startVideoPlayer: currentTime = %d, totalTime = %d, countDownTimer = %d", currentTime, totalTime, countDownTimer));
        });
    }

    /**
     * 转换成时间
     *
     * @param timeMs
     * @return
     */
    public long toTime(long timeMs) {
        if (timeMs <= 0 || timeMs >= 24 * 60 * 60 * 1000) {
            return 0;
        }
        return Math.round((float) timeMs / 1000);
    }

    /**
     * 全屏处理
     */
    public void setStatusBarTransparent() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(0x44000000);
        }
    }
}
